package rollercoaster.environment.utils;

import javax.media.opengl.GL2;
import javax.media.opengl.GL2ES2;

public class Shader {

	private String fragmentShader;
	private String vertexShader;
	
	private int shadingProgram;
	
	public Shader(String fragmentShader, String vertexShader) {
		super();
		this.fragmentShader = fragmentShader;
		this.vertexShader = vertexShader;
	}
	
	public void compileShader(GL2ES2 gl){
		
		shadingProgram=gl.glCreateProgram();
		
		int vShader = loadShader(gl, vertexShader, GL2ES2.GL_VERTEX_SHADER);
		
		int fShader = loadShader(gl, fragmentShader, GL2ES2.GL_FRAGMENT_SHADER);
		
		gl.glAttachShader(shadingProgram, vShader);
		
		gl.glAttachShader(shadingProgram, fShader);
		
		gl.glLinkProgram(shadingProgram);
		
		int[] status=new int[1];
		int[] status2=new int[1];
		((GL2) gl).glGetObjectParameterivARB(shadingProgram, GL2.GL_OBJECT_LINK_STATUS_ARB, status2,0);
		
		System.out.println("Status "+status2[0]);
		if(status2[0]==0){
			System.out.println("Something failed "+status2[0]);
			int len[]=new int[1];
			((GL2) gl).glGetObjectParameterivARB(shadingProgram, GL2.GL_OBJECT_COMPILE_STATUS_ARB,
					len,0);

			byte[] b=new byte[2000];
			((GL2) gl).glGetInfoLogARB(shadingProgram,b.length,status,0,b,0);
		}
		
		gl.glValidateProgram(shadingProgram);
	}
	
	public int getShadingProgram() {
		return shadingProgram;
	}

	private int loadShader(GL2ES2 gl, String shader, int shaderCode) {
		int shaderID = gl.glCreateShader(shaderCode);
		String[] shadersText={shader};
		int[] shaderLength={shader.length()};
		gl.glShaderSource(shaderID, 1, shadersText, shaderLength, 0);
		gl.glCompileShader(shaderID);
		
		int status[]=new int[1];
		
		((GL2) gl).glGetObjectParameterivARB(shaderID,GL2.GL_OBJECT_COMPILE_STATUS_ARB,status,0);
	
		if(status[0]==0){
			System.out.println("Shader has a problem");
			int len[]=new int[1];
			((GL2) gl).glGetObjectParameterivARB(shaderID, GL2.GL_OBJECT_COMPILE_STATUS_ARB,
					len,0);

			byte[] b=new byte[20000];
			((GL2) gl).glGetInfoLogARB(shaderID,b.length,status,0,b,0);
			
			System.out.println(new String(b));
		}else{
			System.out.println("Shader is ok ");
		}
		
		return shaderID;
	}
}
